import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/common_model/mine_points_detail_model.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';
import 'package:yysk_app/model/common_model/mine_points_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/http.dart';

class PointsDetail extends StatefulWidget {
  static const path = '/pointsDetail';
  const PointsDetail({super.key});
  @override
  State<StatefulWidget> createState() => _PointsDetail();
}

class _PointsDetail extends State<PointsDetail> {
  final ScrollController scrollController = ScrollController();
  final GlobalController globalController = Get.find();

  var pageNum = 1;
  var pageSize = 20;
  final list = RxList<MinePointDetailListItem>([]);
  final pointsId = RxString('');
  final amount = RxString('');
  final pointsName = RxString('');
  final pointsImageUrl = RxString('');

  @override
  void initState() {
    super.initState();
    pointsId.value = Get.parameters['pointsId'] ?? Get.arguments['pointsId'];
    amount.value = Get.parameters['amount'] ?? Get.arguments['amount'];
    pointsName.value =
        Get.parameters['pointsName'] ?? Get.arguments['pointsName'];
    pointsImageUrl.value =
        Get.parameters['pointsImageUrl'] ?? Get.arguments['pointsImageUrl'];

    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getPointListData(loadMore: true);
      }
    });
    _handleRefresh();
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: Obx(
              () => Stack(
                children: [
                  SizedBox(
                    width: context.width,
                    child: ImageAssetWidget(
                      width: 375.px,
                      height: 305.px,
                      alignment: Alignment.topCenter,
                      imageUrl: 'static/images/point_bg.png',
                    ),
                  ),
                  // Positioned(
                  //   right: 40.px,
                  //   top: 99.px,
                  //   child: LazyImage(
                  //     imageUrl: pointsImageUrl.value ?? '',
                  //     width: 110,
                  //     height: 110,
                  //   ),
                  // ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: top),
                      CustomAppBar2(title: '积分详情', context: context),
                      hiSpace(height: 50.px),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                width: 220.px,
                                padding: EdgeInsets.only(left: 30.px),
                                child: Text(
                                  pointsName.value,
                                  style: TextStyle(
                                    fontSize: 16.px,
                                    color: AppColors.fontColorGreen,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ),
                              hiSpace(height: 12.px),
                              Container(
                                constraints: BoxConstraints(maxWidth: 230.px),
                                padding: EdgeInsets.only(left: 30.px),
                                child: Text(
                                  amount.value,
                                  textAlign: TextAlign.left,
                                  style: TextStyle(
                                    fontSize: 48.px,
                                    color: Color(0xFF092E3F),
                                    fontWeight: FontWeight.w400,
                                    fontFamily: 'CustomBebas',
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          Padding(
                            padding: EdgeInsets.only(right: 30.px),
                            child: LazyImage(
                              imageUrl: pointsImageUrl.value ?? '',
                              width: 110,
                              height: 110,
                            ),
                          ),
                        ],
                      ),
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.fromLTRB(17, 10, 17, 0),
                          margin: EdgeInsets.only(top: 55.px),
                          child: RefreshAndScrollWidget(
                            onRefresh: _handleRefresh,
                            scrollController: scrollController,
                            itemBuilder: (item, index) => _listItem(item),
                            itemCount: list.length,
                            items: list,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _handleRefresh() async {
    // 获取数据
    getPointListData();
  }

  getPointListData({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      http.netFetch<MinePointDetailListModel>(
        ApiUrl.pointsDetail,
        params: {
          'pageNum': pageNum,
          'pageSize': 20,
          'pointsId': pointsId.value,
        },
        method: Method.post,
        success: (result) {
          List<MinePointDetailListItem> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            list.clear();
          }
          list.addAll(items);
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }

  _listItem(MinePointDetailListItem item) {
    return Container(
      height: 70.px,
      padding: EdgeInsets.all(12.px),
      margin: EdgeInsets.only(bottom: 12.px),
      decoration: BoxDecoration(
        color: AppColors.backgroundColor.withOpacity(0.3),
        borderRadius: BorderRadius.circular(8.px),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    item.activityType == 'IMPORT'
                        ? '资产${item.isAdd == true ? '增加' : '扣减'}'
                        : '${item.activityName}',
                    style: TextStyle(
                      color: AppColors.fontColorBlack,
                      fontSize: 16.px,
                    ),
                  ),
                  item.activityType == 'IMPORT'
                      ? SizedBox(
                        width: 160.px,
                        child: Text(
                          '(${item.remark ?? ''})',
                          style: TextStyle(
                            fontSize: 10.px,
                            color: AppColors.fontColorBlack,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      )
                      : SizedBox(),
                ],
              ),
              Text(
                '${item.createTime}',
                style: TextStyle(
                  fontSize: 14.px,
                  color: AppColors.fontColorGrey,
                ),
              ),
            ],
          ),
          Text(
            '${(item.isAdd == true ? '+' : '-') + item.amount.toString()} ',
            style: TextStyle(
              fontSize: 20.px,
              color: AppColors.fontColorGreen,
              fontFamily: 'CustomFont',
            ),
          ),
        ],
      ),
    );
  }
}
